<template>
  <div class="trackPlayback">
    <Row :gutter="8" style="height: 100%;">
      <Col class="gutter-row list" :span="5" style="display: flex;flex-direction: column">
        <Card dis-hover :bordered="true">
          <template #title>搜索</template>
          <Form ref="formSearch" style="width: 100%" :model="formDataSearch" label-position="top">
            <Row :gutter="8">
              <Col :span="12">
                <FormItem label="车牌号">
                  <i-input v-model="formDataSearch.carPlateNo" placeholder="请输入车牌号码" clearable/>
                </FormItem>
              </Col>
              <Col :span="12">
                <FormItem label="车牌颜色">
                  <Select v-model="formDataSearch.carPlateColor">
                    <Option v-for="item in colorList" :value="item.value" :key="item.value">{{ item.label }}</Option>
                  </Select>
                </FormItem>
              </Col>
            </Row>
            <FormItem label="查询天数">
              <RadioGroup v-model="formDataSearch.type" type="button" button-style="solid" @change="dayChange">
                <Radio label="1">一天内</Radio>
                <Radio label="2">两天内</Radio>
                <Radio label="3">三天内</Radio>
                <!--                <Radio label="-1">自定义</Radio>-->
              </RadioGroup>
            </FormItem>
            <FormItem label="时间范围">
              <DatePicker
                  type="datetimerange"
                  style="width: 100%"
                  format="yyyy-MM-dd HH:mm:ss"
                  placeholder="选择时间范围"
                  v-model="formDataSearch.datetimerange"
              />
            </FormItem>
            <Button type="primary" @click="searchSubmit" long :disabled="isSearch">搜索</Button>
          </Form>
        </Card>

        <Card dis-hover :bordered="true" class="left-bottom-view">
          <template #title>轨迹信息</template>
          <div class="data-g-view">
            <div class="data-cell">
              <div class="data-key">车牌号码</div>
              <div class="data-value">{{ trajectoryInfo.carPlateNo }}</div>
            </div>
            <div class="data-cell">
              <div class="data-key">总里程</div>
              <div class="data-value">{{ trajectoryInfo.totalMileage }} km</div>
            </div>
            <div class="data-cell">
              <div class="data-key">行驶里程</div>
              <div class="data-value">{{ trajectoryInfo.mileage }} km</div>
            </div>
            <div class="data-cell">
              <div class="data-key">最高时速</div>
              <div class="data-value">{{ trajectoryInfo.highSpeed }} km/h</div>
            </div>
            <div class="data-cell">
              <div class="data-key">平均速度</div>
              <div class="data-value">{{ trajectoryInfo.averageSpeed }} km/h</div>
            </div>
            <div class="data-cell">
              <div class="data-key">最高海拔</div>
              <div class="data-value">{{ trajectoryInfo.highAltitude }} 米</div>
            </div>
          </div>

          <div class="data-g-view" style="grid-template-columns: 1fr;margin-top: 10px">
            <div class="data-cell">
              <div class="data-key">开始时间</div>
              <div class="data-value">{{ trajectoryInfo.startTime }}</div>
            </div>
            <div class="data-list-cell">{{ trajectoryInfo.startLocation }}</div>
            <div class="data-cell">
              <div class="data-key">结束时间</div>
              <div class="data-value">{{ trajectoryInfo.endTime }}</div>
            </div>
            <div class="data-list-cell">{{ trajectoryInfo.endLocation }}</div>
          </div>

          <div class="bottom-speed-view">
            <div class="border f-r-c">
              <Icon v-if="!isPlay" type="md-play" size="18" @click="playMap" />
              <Icon v-else type="md-pause" size="18" @click="pauseMap"/>
              <Icon type="md-square" style="margin-left: 8px" size="18" @click="stopMap"/>
              <Progress
                :percent="trajectoryList.length > 0 ? (currentPosition / trajectoryList.length) * 100 : 0"
                :stroke-width="5"
                :hide-info="true"
                style="margin-left: 8px" />
            </div>
          </div>

          <RadioGroup v-model="formDataSearch.speed" type="button" button-style="solid" @change="e => {
                if(isPlay){
                  playMap()
                }
              }">
            <Radio :label="1">一倍速</Radio>
            <Radio :label="2">二倍速</Radio>
            <Radio :label="3">三倍速</Radio>
<!--            <Radio :label="4">四倍速</Radio>-->
            <Radio :label="5">五倍速</Radio>
          </RadioGroup>
        </Card>
      </Col>
      <Col class="gutter-row" :span="19">
        <div class="right-view">
          <Card dis-hover :bordered="true" class="right-top-view">
            <div id="xd_map" class="map-view"></div>
            <div class="b-r-v">
              <RadioGroup v-model="analyzeType" type="button" button-style="solid" @on-change="e => {initCharts()}">
                <Radio :label="1">轨迹分析</Radio>
                <Radio :label="2">速度分析</Radio>
              </RadioGroup>
            </div>
          </Card>

          <Card dis-hover :bordered="true" class="right-bottom-view" :padding="6">
            <div v-show="analyzeType == 1" style="display: flex;flex-direction: row;height: 100%;">
              <Card dis-hover :bordered="true" style="width: 300px;height: 100%" :padding="6">
                <div id="gaugeCharts" style="width: 100%;height: 100%"></div>
              </Card>
              <Card dis-hover :bordered="true" style="height: 100%;margin-left: 6px" :padding="6">
                <div class="position-cell position-cell-bg-grey">
                  <div style="width: 50px;font-weight: bold;">序号</div>
                  <div style="width: 70px;font-weight: bold;">方向</div>
                  <div style="width: 100px;font-weight: bold;">车牌号</div>
                  <div style="width: 80px;font-weight: bold;">速度</div>
                  <div style="flex: 1;font-weight: bold;">定位时间</div>
                </div>
                <div ref="scrollRef" style="height:calc(100% - 36px); overflow: scroll;overflow-x: hidden">
                  <div v-for="(item,index) in trajectoryList"
                       class="position-cell"
                       :class="[index % 2 ? '' : 'position-cell-bg-grey',currentPosition == index? 'position-cell-bg-blue' : '' ]">
                    <div style="width: 50px;">{{ index + 1 }}</div>
                    <div style="width: 70px;">{{ item.directionName }}</div>
                    <div style="width: 100px;">{{ item.carPlateNo }}</div>
                    <div style="width: 80px;">{{ item.vec1 }}km/h</div>
                    <div style="flex: 1;">{{ item.dateTime }}</div>
                  </div>
                </div>
              </Card>
              <Card dis-hover :bordered="true" style="height: 100%;flex: 1;margin-left: 6px" :padding="6">
                <xdTable ref="tableParkingRef" :tableData="tableParkingData"></xdTable>
              </Card>
            </div>
            <div v-show="analyzeType == 2" id="speedCharts" style="width: 100%;height: 100%"></div>
          </Card>
        </div>
      </Col>
    </Row>
  </div>
</template>
<script setup>
import {inject, reactive, ref, resolveComponent, nextTick, onMounted, onUnmounted} from 'vue'
import end from '@/assets/track/end.png'
import b1 from '@/assets/track/b_1.png'
import start from '@/assets/track/start.png'
import stop from '@/assets/track/icon_stop.png'
const apiUrl = inject('$apiUrl') //接口调用
const $axios = inject('$axiosInterceptor');// 变量全局化 axios
const $echarts = inject('$echarts');//自己封装的方法
import xdTable from '@/components/table/index.vue'

const $ViewUIPlus = inject('$ViewUIPlus');//引用全局组件
const $common = inject('$common');//自己封装的方法

onMounted(() => {//mounted 挂载结束状态  // console.log("App ===> 相当于 vue2.x 中 mounted")
  //处理时间显示
  handleTime(1)
  mapLoad();
  initGaugeCharts()
})

onUnmounted( () => {
  clearTimer()
})

/**
 *搜索条件
 */
const formDataSearch = reactive({
  type: "1",
  datetimerange: [],
  carPlateNo:'',
  carPlateColor:'2',
  speed:1,
  parkStatus:true,
})

/**
 * 轨迹信息详情
 */
const trajectoryInfo = reactive({
  carPlateNo:"--",
  totalMileage:"--",
  mileage:"--",
  averageSpeed:"--",
  highSpeed:"--",
  highAltitude:"--",
  startTime:'--',
  endTime:'--',
  startLocation:'--',
  endLocation:'--'
})

//地图加载
const state = reactive({
  map: null,//地图
});

/**
 * 是否正在播放轨迹
 * @type {Ref<UnwrapRef<boolean>>}
 */
const isPlay = ref(false)

/**
 * 是否正在搜索轨迹
 * @type {Ref<UnwrapRef<boolean>>}
 */
const isSearch = ref(false)

/**
 * 地图的分析类型 1轨迹分析 2速度分析 3停车分析
 * @type {Ref<UnwrapRef<boolean>>}
 */
const analyzeType = ref(1)

/**
 * 轨迹播放使用的timer
 */
const mapTimer = ref(null)

/**
 * 车牌颜色
 */
const colorList = [
  {
    value: '2',
    label: '黄色'
  },
  {
    value: '1',
    label: '蓝色'
  },
  {
    value: '5',
    label: '绿色'
  },
  {
    value: '95',
    label: '黄绿色'
  }
]

/**
 * 定位轨迹数据
 */
const trajectoryList = ref([]);

/**
 * 定位轨迹停留点
 */
const vehicleParkingList = ref([]);

const scrollRef = ref();
const xdTableRef = ref();
const tableData = reactive({
  url: "",//请求地址
  method: 'post',//请求方式
  where: {},//搜索条件
  height: '100%',//表格高度 auto
  page: false,//分页是否使用
  dataList:trajectoryList,
  columns: [//表头数据
    {type: 'index', width: 70, align: 'center', title: '序号'},
    {title: '车牌号', minWidth: 100, key:"carPlateNo"},
    {
      title: '车牌颜色', minWidth: 100, key: 'carPlateColor', tooltip: true, render: (h, params) => {
        if (params.row.carPlateColor == 1) {//蓝色
          return h(resolveComponent('Tag'), {type: 'dot', color: 'primary'}, '蓝色');
        } else if (params.row.carPlateColor == 2) {//黄色
          return h(resolveComponent('Tag'), {type: 'dot', color: 'warning'}, '黄色');
        } else if (params.row.carPlateColor == 5) {//绿色
          return h(resolveComponent('Tag'), {type: 'dot', color: 'success'}, '绿色');
        } else if (params.row.carPlateColor == 95) {//黄绿色
          return h(resolveComponent('Tag'), {type: 'dot', color: 'success'}, '黄绿色');
        } else {//其他
          return h(resolveComponent('Tag'), {type: 'dot', color: 'error'}, '其他');
        }
      }
    },
    {title: '定位时间',minWidth: 140, key:"dateTime"},
    {title: '速度',minWidth: 100, key:"vec1",render: (h, params) => {
        return h('span', {}, `${params.row.vec1}km/h`)
      }},
    {title: '总里程数',minWidth: 100, key:"vec3",render: (h, params) => {
        return h('span', {}, `${params.row.vec3}km`)
      }},
    {title: '方向', minWidth: 100, key:"directionName"},
    {title: '海拔高度', minWidth: 100, key:"altitude",render: (h, params) => {
        return h('span', {}, `${params.row.altitude}米`)
      }},
    {title: '定位经度', minWidth: 120, key:"lonX"},
    {title: '定位纬度', minWidth: 120, key:"latY"},
  ],
  pagingParameters: {// 分页参数
    page: 'pageNo',
    limit: 'pageSize'
  },
  format: {//返回数据格式
    list: ['data'],//数据list
    count: ['count'],//数据总量
  },
})

const tableParkingRef = ref();
const tableParkingData = reactive({
  url: "",//请求地址
  method: 'post',//请求方式
  where: {},//搜索条件
  height: '100%',//表格高度 auto
  page: false,//分页是否使用
  dataList:vehicleParkingList,
  columns: [//表头数据
    {type: 'index', width: 70, align: 'center', title: '序号'},
    // {title: '车牌号', minWidth: 100, key:"carPlateNo"},
    // {
    //   title: '车牌颜色', minWidth: 100, key: 'carPlateColor', tooltip: true, render: (h, params) => {
    //     if (params.row.carPlateColor == 1) {//蓝色
    //       return h(resolveComponent('Tag'), {type: 'dot', color: 'primary'}, '蓝色');
    //     } else if (params.row.carPlateColor == 2) {//黄色
    //       return h(resolveComponent('Tag'), {type: 'dot', color: 'warning'}, '黄色');
    //     } else if (params.row.carPlateColor == 5) {//绿色
    //       return h(resolveComponent('Tag'), {type: 'dot', color: 'success'}, '绿色');
    //     } else if (params.row.carPlateColor == 95) {//黄绿色
    //       return h(resolveComponent('Tag'), {type: 'dot', color: 'success'}, '黄绿色');
    //     } else {//其他
    //       return h(resolveComponent('Tag'), {type: 'dot', color: 'error'}, '其他');
    //     }
    //   }
    // },
    {title: '停留开始时间',minWidth: 140, key:"startTime"},
    // {title: '停留结束时间',minWidth: 140, key:"endTime"},
    {title: '持续时长',minWidth: 100, key:"duration",render: (h, params) => {
        return h('span', {}, `${$common.timeConversion(params.row.duration)}`)
      }},
    {title: '停留位置', minWidth: 220, key:"loc"}
  ],
  pagingParameters: {// 分页参数
    page: 'pageNo',
    limit: 'pageSize'
  },
  format: {//返回数据格式
    list: ['data'],//数据list
    count: ['count'],//数据总量
  },
  onCurrentChange:(currentRow, oldCurrentRow)=>{
    state.map.setZoom(17)
    setTimeout(() => {
      state.map.setCenter(new BMap.Point(currentRow.lonX_B, currentRow.latY_B))
    },200)
    pauseMap()
  }

})

const gaugeChart = ref(null)

/**
 * 初始化图表
 */
const initGaugeCharts = () => {
  let chartDom = document.getElementById('gaugeCharts');
  gaugeChart.value = $echarts.init(chartDom);
  let option = {
    grid: [
      {
        bottom: '10px',
        left:"10px",
        top:"10px",
        right:"10px"
      }
    ],
    series: [
      {
        type: 'gauge',
        axisLine: {
          lineStyle: {
            width: 30,
            color: [
              [0.3, '#67e0e3'],
              [0.7, '#37a2da'],
              [1, '#fd666d']
            ]
          }
        },
        pointer: {
          itemStyle: {
            color: 'auto'
          }
        },
        axisTick: {
          distance: -30,
          length: 8,
          lineStyle: {
            color: '#fff',
            width: 2
          }
        },
        splitLine: {
          distance: -30,
          length: 30,
          lineStyle: {
            color: '#fff',
            width: 4
          }
        },
        axisLabel: {
          color: 'inherit',
          distance: 40,
          fontSize: 12
        },
        detail: {
          valueAnimation: true,
          formatter: '{value} km/h',
          color: 'inherit',
          fontSize: 12
        },
        data: [
          {
            value: 0
          }
        ]
      }
    ]
  };
  option && gaugeChart.value.setOption(option);
}

const myChart = ref(null)
/**
 * 初始化图表
 */
const initCharts = () => {
  setTimeout(() => {
    if(analyzeType.value == 2 && !myChart.value){
      let chartDom = document.getElementById('speedCharts');
      myChart.value = $echarts.init(chartDom);
      setLineChartsData()
    }else if(myChart.value){
      setLineChartsData()
    }
  },300)
}

/**
 * 设置折线图的数据
 */
const setLineChartsData = () => {
  const data = [];
  let dateList = [];
  let valueList = [];
  //处理数据
  if(trajectoryList.value && trajectoryList.value.length >0){
    trajectoryList.value.forEach(item => {
      data.push([item.dateTime,item.vec1])
    })
    dateList = data.map(function (item) {
      return item[0];
    });
    valueList = data.map(function (item) {
      return item[1];
    });
  }

  let option = {
    tooltip: {
      trigger: 'axis'
    },
    xAxis: [
      {
        data: dateList
      }
    ],
    yAxis: [
      {}
    ],
    grid: [
      {
        bottom: '8%',
        left:"4%",
        top:"4%",
        right:"2%"
      }
    ],
    series: [
      {
        type: 'line',
        showSymbol: false,
        data: valueList
      }
    ]
  };
  option && myChart.value.setOption(option);
}

/**
 * 地图轨迹开始播放
 */
const playMap = () => {
  if(trajectoryList.value && trajectoryList.value.length > 0){
    isPlay.value = true
    clearTimer()
    mapTimer.value = setInterval(() => {
      mapAdd()
    },parseInt(1000 / formDataSearch.speed))
  }else{
    let msg = $ViewUIPlus.Message.error({
      content: '请先搜索轨迹',
      duration: 0
    });
    setTimeout(msg,1500)
  }
}

/**
 * 清空定时器
 */
const clearTimer = () => {
  console.log("clearTimer")
  if(mapTimer.value){
    clearInterval(mapTimer.value)
    mapTimer.value = null
  }
}

/**
 * 地图轨迹暂停播放
 */
const pauseMap = () => {
  isPlay.value = false
  clearTimer()
}

/**
 * 地图轨迹停止播放
 */
const stopMap = () => {
  isPlay.value = false
  currentPosition.value = 0
  if(marker.value){
    state.map.removeOverlay(marker.value)
    marker.value = null
  }
  clearTimer()
  scrollRef.value.scrollTop = 0
}

/**
 * 滚动定位列表
 */
const listScroll = () => {
  let height = currentPosition.value * 36
  if(height > 36 * 5){
    scrollRef.value.scrollTop = height - 36 * 5
  }
}

/**
 * 创建地图轨迹
 */
const createMapTrack = () => {
  let line = [];
  state.map.clearOverlays()
  trajectoryList.value.forEach((k, i) =>  {
    let marker;
    if (i == 0) {//起点

      let myIcon = new BMap.Icon(start, new BMap.Size(28, 62));
      marker = new BMap.Marker(new BMap.Point(k.lonX, k.latY), {icon: myIcon});  // 创建标注
      marker.setZIndex(9999);
      state.map.addOverlay(marker);            //增加点

      let opts = {
        width : 320,     // 信息窗口宽度
        height: 160,     // 信息窗口高度
        title : "<h1 style='margin-left:10px;font-weight:900'>轨迹起点位置</h1>", // 信息窗口标题
      }

      let content = `<div style="line-height: 30px;overflow: auto;height: 160px">
                <span style='display:inline-block;width:80px; text-align: left;font-weight:700'>定位时间：</span>`+
          k.dateTime+
          "<br/>" +
          `<span style='display:inline-block;width:80px; text-align: left;font-weight:700'>当前里程：</span>` +
          k.vec3 +
          "<br/>" +
          `<span style='display:inline-block;width:80px; text-align: left;font-weight:700'>当前车速：</span>` +
          k.vec1 +
          "<br/>" +
          `<span style='display:inline-block;width:80px; text-align: left;font-weight:700'>当前位置：</span>`+
          k.location + `
          </div>`

      let infoWindow = new BMap.InfoWindow(content, opts);  // 创建信息窗口对象

      //点标记添加点击事件infoWindow
      marker.addEventListener('click', function () {
        state.map.openInfoWindow(infoWindow,new BMap.Point(k.lonX, k.latY)); // 开启信息窗口
      });

    }else if ((i + 1) == trajectoryList.value.length) {//终点
      let myIcon = new BMap.Icon(end, new BMap.Size(28, 62));
      marker = new BMap.Marker(new BMap.Point(k.lonX, k.latY), {icon: myIcon});  // 创建标注
      marker.setZIndex(9999);
      state.map.addOverlay(marker);            //增加点

      let opts = {
        width : 320,     // 信息窗口宽度
        height: 160,     // 信息窗口高度
        title : "<h1 style='margin-left:10px;font-weight:900'>轨迹终点位置</h1>", // 信息窗口标题
      }

      let content = `<div style="line-height: 30px;overflow: auto;height: 160px">
                <span style='display:inline-block;width:80px; text-align: left;font-weight:700'>定位时间：</span>`+
          k.dateTime+
          "<br/>" +
          `<span style='display:inline-block;width:80px; text-align: left;font-weight:700'>当前里程：</span>` +
          k.vec3 +
          "<br/>" +
          `<span style='display:inline-block;width:80px; text-align: left;font-weight:700'>当前车速：</span>` +
          k.vec1 +
          "<br/>" +
          `<span style='display:inline-block;width:80px; text-align: left;font-weight:700'>当前位置：</span>`+
          k.location + `
          </div>`

      let infoWindow = new BMap.InfoWindow(content, opts);  // 创建信息窗口对象

      //点标记添加点击事件infoWindow
      marker.addEventListener('click', function () {
        state.map.openInfoWindow(infoWindow,new BMap.Point(k.lonX, k.latY)); // 开启信息窗口
      });
    }

    line.push(new BMap.Point(k.lonX, k.latY));//线连接点
  })

  let polyline = new BMap.Polyline(line, {
    strokeWeight: 4,//折线的宽度，以像素为单位
    strokeOpacity: 0.8,//折线的透明度，取值范围0 - 1
    strokeColor: "#1890ff" //折线颜色
  });//

  state.map.addOverlay(polyline);          //增加折线
  state.map.setViewport(line);

  //设置速度分析图标
  initCharts()
  //创建所有停留点
  createMapStopParking()
}

/**
 * 创建所有停留点
 */
const createMapStopParking = () =>{
  if (vehicleParkingList.value && vehicleParkingList.value.length>0){
    vehicleParkingList.value.forEach( (k, i) => {
      let myIcon = new BMap.Icon(stop, new BMap.Size(21, 46));
      myIcon.setImageSize(new BMap.Size(21, 24));
      let marker = new BMap.Marker(new BMap.Point(k.lonX_B, k.latY_B), {icon: myIcon});  // 创建标注
      marker.setZIndex(9999);
      state.map.addOverlay(marker);   //增加点
      createInfoWindow(k,true,marker)
    });
  }
}

/**
 * 创建信息窗口
 */
const createInfoWindow = (data,type,marker) => {
  var opts = {
    width : 300,     // 信息窗口宽度
    // height: 160,     // 信息窗口高度
    title : "<h3 style='margin-left:10px;font-weight:800'>停车点</h3>", // 信息窗口标题
  }

  var location = data.loc ? data.loc : '';

  var content = `<div style="line-height: 30px;">
          <span style='display:inline-block;width:75px; text-align: left;font-weight:700'>开始时间：</span>`+
      data.startTime+
      "<br/>" +
      `<span style='display:inline-block;width:75px; text-align: left;font-weight:700'>结束时间：</span>` +
      data.endTime +
      "<br/>" +
      `<span style='display:inline-block;width:75px; text-align: left;font-weight:700'>停车时长：</span>` +
      $common.timeConversion(data.duration * 60) +
      "<br/>" +
      `<span style='display:inline-block;width:45px; text-align: left;font-weight:700'>位置：</span>`+
      location + `
          </div>`

  var infoWindow = new BMap.InfoWindow(content, opts);  // 创建信息窗口对象

  if (type){
    //点标记添加点击事件infoWindow
    marker.addEventListener('click', () =>  {
      state.map.openInfoWindow(infoWindow,new BMap.Point(data.lonX_B, data.latY_B)); // 开启信息窗口
    });
  }else {
    state.map.openInfoWindow(infoWindow,new BMap.Point(data.lonX_B, data.latY_B)); // 开启信息窗口
  }
}

/**
 * 轨迹播放
 */
const trajectoryPlayback = () => {
  isPlay.value = true;
  that.removeTiming();
  that.timingMethod = setInterval(function () {
    that.removeTiming();
    if (that.positioningindex < that.vehiclePositionEntities.length) {
      that.mapAdd();
      that.trajectoryPlayback();
    } else {
      that.$message.success('播放完毕');
      that.statePlay = false;
      that.removeTiming();
    }
  }, that.speed)
}

/**
 * 当前播放的定位点下标
 */
const currentPosition = ref(0)
/**
 * 移动的marker
 */
const marker = ref(null)

/**
 * 地图加点
 */
const mapAdd = () => {
  let data = trajectoryList.value[currentPosition.value]
  let myIcon = new BMap.Icon(b1, new BMap.Size(22, 22));
  setGaugeSpeed(data.vec1)
  //删除上一个marker
  if(marker.value){
    state.map.removeOverlay(marker.value)
    marker.value = null
  }
  marker.value = new BMap.Marker(new BMap.Point(data.lonX, data.latY), {icon: myIcon,id:2});  // 创建标注
  marker.value.setRotation(data.direction);
  marker.value.setZIndex(999999);
  let html = '<div style=\'background:#FFFFFF;color:#000000;font-weight:normal;padding: 1px;border:solid  1px #ccc\'>' +
      '<div>行驶速度：' + data.vec1 + ' / ' + data.vec2 + '</div>' +
      '<div>总里程数：' + data.vec3 + '公里</div>' +
      '<div>行驶状态： ' + ((data.state >> 0 & 1) ? '启动' : '熄火') + ((data.state >> 1 & 1) ? ' - 定位' : ' - 未定位') + '</div>' +
      '<div>报警状态： ' + ((data.alarm >> 1 & 1) ? '超速报警' : "无超速") + ((data.alarm >> 2 & 1) ? '-疲劳报警' : " - 无疲劳") + '</div>' +
      '<div>定位时间：' + data.dateTime + '</div>' +
      '</div>';
  let BaiMakerLabel = new BMap.Label(html, {offset: new BMap.Size(22, -3)});
  BaiMakerLabel.setStyle({border: 'none', padding: '3px 5px', background: 'none'});
  marker.value.setLabel(BaiMakerLabel);
  state.map.addOverlay(marker.value);//增加点
  if (!checkPoiInMapBound(new BMap.Point(data.lonX, data.latY))) {
    state.map.setCenter(new BMap.Point(data.lonX, data.latY));
  }
  currentPosition.value++;
  listScroll()
}

/**
 * 设置表盘的速度
 */
const setGaugeSpeed = (speed) => {
  gaugeChart.value.setOption({
    series: [
      {
        data: [
          {
            value: speed
          }
        ]
      }
    ]
  });
}

/**
 * 用于判断轨迹回放时经纬度是否超出地图可见区域，若超出则居中
 */
const checkPoiInMapBound = (ThisLatlon) => {
  var mapBounds = state.map.getBounds();
  if (mapBounds.containsPoint(ThisLatlon)) {
    return true;
  } else {
    return false;
  }
}

/**
 * 处理时间
 * @param day
 */
const handleTime = (day) => {
  let date = new Date()
  let endTime = $common.timeFormatting(date, 'yyyy-MM-dd hh:mm:ss')
  date.setDate(date.getDate() - day)
  let startTime = $common.timeFormatting(date, 'yyyy-MM-dd hh:mm:ss')
  formDataSearch.datetimerange = [startTime, endTime]
}

/**
 * 查询天数变化
 * @param e
 */
const dayChange = (e) => {
  handleTime(parseInt(formDataSearch.type))
}

/**
 * 地图初始化
 */
const mapLoad = () => {
  state.map = new BMap.Map("xd_map");    // 创建Map实例
  state.map.centerAndZoom(new BMap.Point(114.498568, 37.076814), 9);  // 初始化地图,设置中心点坐标和地图级别
  //添加地图类型控件
  state.map.addControl(new BMap.MapTypeControl({
    mapTypes: [
      BMAP_NORMAL_MAP,
      BMAP_HYBRID_MAP
    ]
  }));
  state.map.setCurrentCity("邢台");          // 设置地图显示的城市 此项是必须设置的
  state.map.enableScrollWheelZoom(true);     //开启鼠标滚轮缩放
  // 左上角，添加比例尺
  let top_left_control = new BMap.ScaleControl({anchor: BMAP_ANCHOR_TOP_LEFT});
  state.map.addControl(top_left_control);
  //左上角，添加默认缩放平移控件
  let top_left_navigation = new BMap.NavigationControl();
  state.map.addControl(top_left_navigation);
}

/**
 * 搜索轨迹
 */
const searchSubmit = () => {
  if(!formDataSearch.carPlateNo){
    let msg = $ViewUIPlus.Message.error({
      content: '车牌号不能为空',
      duration: 0
    });
    setTimeout(msg,1500)
    return
  }

  checkCarInfo()

}

/**
 * 检查车辆信息，是否入网、是否本籍的车
 */
const checkCarInfo = () => {
  let msg = $ViewUIPlus.Message.loading({
    content: '轨迹查询中...',
    duration: 0
  });
  isSearch.value = true
  $axios.post(apiUrl.coreVehicleCoreVehicleInfo,formDataSearch).then((res) => {
    isSearch.value = false
    let data = res.data.data
    if(!data){
      msg()
      $ViewUIPlus.Message.warning("未查询到车辆信息")
      return
    }else if(data.internetState != 1){
      msg()
      $ViewUIPlus.Message.warning("车辆未入网无法查询轨迹")
      return
    }
    getTrajectory(msg)
  }).catch((err) => {
    isSearch.value = false
    msg()
  })
}

/**
 * 获取轨迹信息
 */
const getTrajectory = (msg) => {
  let data = Object.assign({},formDataSearch);
  data.startTime = $common.timeFormatting(new Date(data.datetimerange[0]),"yyyy-MM-dd hh:mm:ss")
  data.endTime = $common.timeFormatting(new Date(data.datetimerange[1]),"yyyy-MM-dd hh:mm:ss")
  isSearch.value = true
  $axios.post(apiUrl.positionTrajectory,data).then((res) => {
    isSearch.value = false
    msg()
    handleMapData(res.data.data)
  }).catch((err) => {
    isSearch.value = false
    msg()
  })
}

/**
 * 处理轨迹数据
 */
const handleMapData = (data) => {
  if( data && data.vehicleTrajectory && data.vehicleTrajectory.length > 0){
    trajectoryList.value = data.vehicleTrajectory
    vehicleParkingList.value = data.vehicleParking
    handleInfo()
    createMapTrack()
  }else{
    $ViewUIPlus.Message.error("未查询到轨迹信息")
  }
}

/**
 * 处理轨迹详情数据
 * @param data
 */
const handleInfo = () => {
  //起点
  let startPosition = trajectoryList.value[0]
  //终点
  let endPosition = trajectoryList.value[trajectoryList.value.length - 1]
  //赋值定位信息
  trajectoryInfo.startLocation = startPosition.location
  trajectoryInfo.startTime = startPosition.dateTime
  trajectoryInfo.endLocation = endPosition.location
  trajectoryInfo.endTime = endPosition.dateTime
  //赋值车牌号
  trajectoryInfo.carPlateNo = formDataSearch.carPlateNo
  //赋值总里程
  trajectoryInfo.totalMileage = endPosition.vec3
  //计算行驶里程
  trajectoryInfo.mileage = endPosition.vec3 - startPosition.vec3
  //计算最高海拔和速度
  let highAltitude = 0
  let highSpeed = 0
  let totalSpeed = 0
  trajectoryList.value.forEach(item => {
    totalSpeed += item.vec1
    if(highSpeed < item.vec1){
      highSpeed = item.vec1
    }
    if(highAltitude < item.altitude){
      highAltitude = item.altitude
    }
  })
  trajectoryInfo.highSpeed = highSpeed
  trajectoryInfo.highAltitude = highAltitude
  //计算平均速度
  trajectoryInfo.averageSpeed = parseInt(totalSpeed / trajectoryList.value.length)
}

</script>
<style lang="less">
.trackPlayback {
  height: 100%;
  padding: 10px;

  .top-view {
    width: 100%;
    background-color: #ffffff;
    padding: 20px 20px 0px 20px;
  }

  .left-bottom-view {
    flex: 1;
    margin-top: 10px;
    background-color: #ffffff;
    position: relative;

    .title-view{
      margin-bottom: 8px;
      font-weight: bold;
    }

    .data-g-view{
      background-color: rgba(0,0,0,0.13);
      padding: 1px;
      display: grid;
      grid-template-columns:1fr 1fr;
      grid-gap: 1px 1px;
    }

    .data-cell{
      display: flex;
      flex-direction: row;
      align-items: center;
      height: 40px;
      background-color: #ffffff;
      font-size: 13px;

      .data-key{
        width: 82px;
        height: 100%;
        line-height: 40px;
        text-align: center;
        background-color: #f4f4f4;
      }
      .data-value{
        flex: 1;
        height: 100%;
        padding-left: 20px;
        line-height: 40px;
      }
    }

    .data-list-cell{
      padding: 10px;
      background-color: #ffffff;
      font-size: 13px;
    }

    .bottom-speed-view{
      width: 100%;
      margin-top: 10px;
      margin-bottom: 10px;

      .border{
        border: 1px solid rgba(0,0,0,0.1);
      }

      .f-r-c{
        display: flex;
        flex-direction: row;
        align-items: center;
        padding: 10px;
      }
    }
  }

  .right-view{
    width: 100%;
    height: 100%;

    .right-top-view{
      position:relative;
      width: 100%;
      height: calc(100% - 308px);

      .map-view{
        position:absolute;
        right: 6px;
        bottom: 6px;
        top: 6px;
        left: 6px;
      }

      .b-r-v{
        position:absolute;
        right: 0;
        bottom: 0;
        width: 100%;
        z-index: 999;
        padding: 8px;
        display: flex;
        flex-direction: row;
        justify-content: end;
      }

    }

    .right-bottom-view{
      width: 100%;
      margin-top: 8px;
      height: 300px;
      padding: 0px;
      overflow: hidden;
    }
  }

  .ivu-card-body {
    height: 100%;
  }

  .list {
    .ivu-card-body {
      height: calc(100% - 41px);
    }
  }

  .position-cell{
    width: 461px;
    display: flex;
    height: 36px;
    align-items: center;
    padding: 0 20px;
    font-size: 12px;
    border-bottom: 1px solid rgba(0,0,0,0.1);
  }
  .position-cell-bg-grey{
    background-color: #f8f8f9;
  }
  .position-cell-bg-blue{
    background-color: #1890ff;
    color: #ffffff;
  }
}
</style>
